package com.dudy.authdemo.controller;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.dudy.authdemo.model.Menu;
import com.dudy.authdemo.service.MenuService;
import com.dudy.authdemo.vo.MenuVO;
import com.dudy.common.base.CommonResponse;
import com.dudy.common.base.PageData;
import com.dudy.common.base.ResultCode;
import com.dudy.common.util.DingTalkUtil;
import com.dudy.common.util.ResponseUtils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import tk.mybatis.mapper.entity.Example;

/**
 * @program: auth_demo
 * @author: dudy
 * @create: 2020-12-24 10:43
 * @description:
 **/
@RestController
@RequestMapping("/menu")
public class MenuController {

    private static final Logger log = LoggerFactory.getLogger(MenuController.class);

    @Autowired
    private MenuService menuService;

    @PostMapping("/addMenu")
    public CommonResponse<MenuVO> addMenu(MenuVO menuVO) {
        if (menuVO == null) {
            return ResponseUtils.getResponse(ResultCode.REQUEST_PARAM_NULL);
        }
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuVO, menu);
        menu.setCreator(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        menu.setGmtCreateTime(new Date());
        menu.setGmtUpdateTime(new Date());
        menu.setDeleteFlag((byte) 0);
        try {
            int insert = menuService.insert(menu);
            if (insert == 1) {
                return ResponseUtils.getResponse(ResultCode.SUCCESS);
            } else {
                return ResponseUtils.getResponse(ResultCode.FAIL.getCode(), "操作失败，请重试");
            }
        } catch (Exception e) {
            log.error("MenuController addMenu error,请求参数：{}", JSONObject.toJSONString(menuVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "addMenu", JSONObject.toJSONString(menuVO)
                    , e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @PostMapping("/updateMenu")
    public CommonResponse<MenuVO> updateMenu(MenuVO menuVO) {
        if (menuVO == null || menuVO.getId() == null) {
            return ResponseUtils.getResponse(ResultCode.REQUEST_PARAM_NULL);
        }
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuVO, menu);
        menu.setUpdater(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        menu.setGmtUpdateTime(new Date());
        try {
            int update = menuService.updateByPrimaryKey(menu);
            if (update == 1) {
                return ResponseUtils.getResponse(ResultCode.SUCCESS);
            } else {
                return ResponseUtils.getResponse(ResultCode.FAIL.getCode(), "操作失败，请重试");
            }
        } catch (Exception e) {
            log.error("MenuController update error,请求参数：{}", JSONObject.toJSONString(menuVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "update", JSONObject.toJSONString(menuVO),
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryMenuById")
    public CommonResponse<MenuVO> queryMenuById(@RequestParam("id") long id) {
        Menu menu = new Menu();
        menu.setId(id);
        try {
            MenuVO menuVO = menuService.selectByPrimaryKey(menu);
            return ResponseUtils.getResponse(ResultCode.SUCCESS);
        } catch (Exception e) {
            log.error("MenuController queryMenuById error,请求参数：{}", id, e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryMenuById", id + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryMenuByExample")
    public CommonResponse<List<MenuVO>> queryMenuByExample(MenuVO menuVO) {
        Example example = new Example(Menu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        if (StringUtils.isNotBlank(menuVO.getMenuName())) {
            criteria.andLike("menuName", menuVO.getMenuName());
        }
        if (StringUtils.isNotBlank(menuVO.getMenuCode())) {
            criteria.andEqualTo("menuCode", menuVO.getMenuCode());
        }
        try {
            List<MenuVO> menuVOS = menuService.selectByExample(example);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, menuVOS);
        } catch (Exception e) {
            log.error("MenuController queryMenuByExample error,请求参数：{}", JSONObject.toJSONString(menuVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryMenuByExample",
                    JSONObject.toJSONString(menuVO) + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    /**
     * 精确匹配查询
     *
     * @param menuVO
     * @return
     */
    @GetMapping("/queryMenuExactly")
    public CommonResponse<List<MenuVO>> queryMenuExactly(MenuVO menuVO) {
        Example example = new Example(Menu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        if (StringUtils.isNotBlank(menuVO.getMenuName())) {
            criteria.andEqualTo("menuName", menuVO.getMenuName());
        }
        if (StringUtils.isNotBlank(menuVO.getMenuCode())) {
            criteria.andEqualTo("menuCode", menuVO.getMenuCode());
        }
        if (StringUtils.isNotBlank(menuVO.getMenuUrl())) {
            criteria.andEqualTo("menuUrl", menuVO.getMenuUrl());
        }
        try {
            List<MenuVO> menuVOS = menuService.selectByExample(example);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, menuVOS);
        } catch (Exception e) {
            log.error("MenuController queryMenuByExample error,请求参数：{}", JSONObject.toJSONString(menuVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryMenuByExample",
                    JSONObject.toJSONString(menuVO) + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryMenuPage")
    public CommonResponse<PageData<MenuVO>> queryMenuPage(MenuVO menuVO) {
        Example example = new Example(Menu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        if (StringUtils.isNotBlank(menuVO.getMenuName())) {
            criteria.andLike("menuName", menuVO.getMenuName());
        }
        if (StringUtils.isNotBlank(menuVO.getMenuCode())) {
            criteria.andEqualTo("menuCode", menuVO.getMenuCode());
        }
        try {
            PageData<MenuVO> pageData = menuService.selectPageByExample(menuVO, example);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, pageData);
        } catch (Exception e) {
            log.error("MenuController queryMenuPage error,请求参数：{}", JSONObject.toJSONString(menuVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryMenuPage",
                    JSONObject.toJSONString(menuVO) + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryCurrentMenu")
    public CommonResponse<List<MenuVO>> queryCurrentMenu() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        Object credentials = authentication.getCredentials();
        Object details = authentication.getDetails();
        String username =
                ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        try {
            List<MenuVO> menuVOS = menuService.queryCurrentMenu(username);
            return ResponseUtils.getResponse(menuVOS);
        } catch (Exception e) {
            log.error("MenuController queryCurrentMenu error,请求参数：{}", username, e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryCurrentMenu",
                    username + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }
}
